/*
 * BluCOMDeskView.java
 */
package blucomdesk;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.Task;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.bluetooth.*;
import java.util.*;
import javax.swing.DefaultListModel;
import java.io.*;
import javax.swing.DefaultComboBoxModel;

/**
 * The application's main frame.
 */
public class BluCOMDeskView extends FrameView implements DiscoveryListener {

    public BluCOMDeskView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
        
        getFrame().setTitle("BluCOMDesk");        
        getFrame().setIconImage(resourceMap.getImageIcon("blu").getImage());
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = BluCOMDeskApp.getApplication().getMainFrame();
            aboutBox = new BluCOMDeskAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        BluCOMDeskApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        scrlpnlListBluServ = new javax.swing.JScrollPane();
        lstBluServ = new javax.swing.JList();
        cboboxBluDev = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        btnServices = new javax.swing.JButton();
        mnuMain = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        mnuBlu = new javax.swing.JMenu();
        mnuitmSearch = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        scrlpnlListBluServ.setName("scrlpnlListBluServ"); // NOI18N

        lstBluServ.setName("lstBluServ"); // NOI18N
        scrlpnlListBluServ.setViewportView(lstBluServ);

        cboboxBluDev.setName("cboboxBluDev"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(blucomdesk.BluCOMDeskApp.class).getContext().getResourceMap(BluCOMDeskView.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(blucomdesk.BluCOMDeskApp.class).getContext().getActionMap(BluCOMDeskView.class, this);
        btnServices.setAction(actionMap.get("listDevServices")); // NOI18N
        btnServices.setText(resourceMap.getString("btnServices.text")); // NOI18N
        btnServices.setName("btnServices"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addComponent(jLabel1)
                .addContainerGap())
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addComponent(jLabel2)
                .addGap(345, 345, 345))
            .addComponent(scrlpnlListBluServ, javax.swing.GroupLayout.DEFAULT_SIZE, 423, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addComponent(cboboxBluDev, 0, 334, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnServices, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cboboxBluDev, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnServices, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(scrlpnlListBluServ, javax.swing.GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE))
        );

        mnuMain.setName("mnuMain"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        mnuMain.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        mnuMain.add(helpMenu);

        mnuBlu.setText(resourceMap.getString("mnuBluetooth.text")); // NOI18N
        mnuBlu.setName("mnuBluetooth"); // NOI18N

        mnuitmSearch.setAction(actionMap.get("searchBluDev")); // NOI18N
        mnuitmSearch.setText(resourceMap.getString("mnuitmSearch.text")); // NOI18N
        mnuitmSearch.setName("mnuitmSearch"); // NOI18N
        mnuBlu.add(mnuitmSearch);

        mnuMain.add(mnuBlu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 423, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 253, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(mnuMain);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    @Action
    public Task searchBluDev() {
        return new SearchBluDevTask(getApplication());
    }

    private class SearchBluDevTask extends org.jdesktop.application.Task<Object, Void> {
        SearchBluDevTask(org.jdesktop.application.Application app) {
            // Runs on the EDT.  Copy GUI state that
            // doInBackground() depends on from parameters
            // to SearchBluDevTask fields, here.
            super(app);
            
        }
        @Override protected Object doInBackground() {
            cboboxBluDev.removeAllItems();
            devicesDiscovered.clear();            
            cboboxBluDev.addItem("Please select a device from the list");            
            inquiryCompletedEvent = new Object();
            synchronized (inquiryCompletedEvent) {
                try {
                    boolean started = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC,(DiscoveryListener)BluCOMDeskApp.getApplication().getMainView());
                    if (started) {
                        statusMessageLabel.setText("Please wait! Searching...");
                        inquiryCompletedEvent.wait();
                        statusMessageLabel.setText("Found " + devicesDiscovered.size());
                    }
                } catch (BluetoothStateException ex) {
                    statusMessageLabel.setText(ex.getMessage());
                } catch (InterruptedException ex) {
                    statusMessageLabel.setText(ex.getMessage());
                }
            }
            return null;  // return your result
        }
        @Override protected void succeeded(Object result) {
            // Runs on the EDT.  Update the GUI based on
            // the result computed by doInBackground().
        }
    }

    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnServices;
    private javax.swing.JComboBox cboboxBluDev;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JList lstBluServ;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenu mnuBlu;
    private javax.swing.JMenuBar mnuMain;
    private javax.swing.JMenuItem mnuitmSearch;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JScrollPane scrlpnlListBluServ;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;
    public static final Vector/*<RemoteDevice>*/ devicesDiscovered = new Vector();
    public static final Vector/*<ServiceRecord>*/ serviceFound = new Vector();
    Object inquiryCompletedEvent = null;
    Object serviceSearchCompletedEvent = null;
    DefaultComboBoxModel cboboxDevModel = null;
    DefaultListModel listServModel = null;

    public void deviceDiscovered(RemoteDevice btDevice, DeviceClass arg1) {
        devicesDiscovered.add(btDevice);
        try {
            cboboxBluDev.addItem(btDevice.getFriendlyName(false));
        } catch (IOException cantGetDeviceName) {
            cboboxBluDev.addItem(btDevice.getBluetoothAddress());
        }
    }

    public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
        for (int i = 0; i < servRecord.length; i++) {
            String url = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
            if (url == null) {
                continue;
            }
            serviceFound.add(servRecord[i]);
            DataElement serviceName = servRecord[i].getAttributeValue(0x0100);
            if (serviceName != null) {
                listServModel.addElement(serviceName.getValue());                
            } else {
                listServModel.addElement(url);         
            }
        }       
    }

    public void serviceSearchCompleted(int arg0, int arg1) {
        synchronized (serviceSearchCompletedEvent) {
            serviceSearchCompletedEvent.notifyAll();
        }
        lstBluServ.setModel(listServModel);
        lstBluServ.updateUI();
    }

    public void inquiryCompleted(int arg0) {
        synchronized (inquiryCompletedEvent) {
            inquiryCompletedEvent.notifyAll();
        }
    }

    @Action
    public Task listDevServices() {
        return new ListDevServicesTask(getApplication());
    }

    private class ListDevServicesTask extends org.jdesktop.application.Task<Object, Void> {
        ListDevServicesTask(org.jdesktop.application.Application app) {
            // Runs on the EDT.  Copy GUI state that
            // doInBackground() depends on from parameters
            // to ListDevServicesTask fields, here.
            super(app);
        }
        @Override protected Object doInBackground() {
            serviceFound.clear();
            serviceSearchCompletedEvent = new Object();
            if(((String)cboboxBluDev.getSelectedItem()).compareTo("Please select a device from the list") != 0) {
                listServModel = new DefaultListModel();
                synchronized (serviceSearchCompletedEvent) {
                    try {
                        int[] attrIDs = new int[]{0x0100, 0x0003};

                        LocalDevice.getLocalDevice().getDiscoveryAgent().searchServices(attrIDs, getSearchUUIDs(), (RemoteDevice) devicesDiscovered.get(cboboxBluDev.getSelectedIndex() - 1), (DiscoveryListener) BluCOMDeskApp.getApplication().getMainView());
                        statusMessageLabel.setText("Please wait! Searching...");
                        serviceSearchCompletedEvent.wait();
                        statusMessageLabel.setText("Found " + serviceFound.size());
                    } catch (InterruptedException ex) {
                        Logger.getLogger(BluCOMDeskView.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (BluetoothStateException ex) {
                        Logger.getLogger(BluCOMDeskView.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
            return null;
        }
        @Override protected void succeeded(Object result) {
            // Runs on the EDT.  Update the GUI based on
            // the result computed by doInBackground().
        }
    }
    public javax.bluetooth.UUID[] getSearchUUIDs(){
        javax.bluetooth.UUID[] searchUuidSet = new javax.bluetooth.UUID[] { 
//                                                                            new javax.bluetooth.UUID(0x0001), 
//                                                                            new javax.bluetooth.UUID(0x0003),
//                                                                            new javax.bluetooth.UUID(0x0008),
//                                                                            new javax.bluetooth.UUID(0x000C),
//                                                                            new javax.bluetooth.UUID(0x0100),
//                                                                            new javax.bluetooth.UUID(0x000F),
//                                                                            new javax.bluetooth.UUID(0x1101),
//                                                                            new javax.bluetooth.UUID(0x1000),
//                                                                            new javax.bluetooth.UUID(0x1001),
                                                                            new javax.bluetooth.UUID(0x1002)
//                                                                            new javax.bluetooth.UUID(0x1105),
//                                                                            new javax.bluetooth.UUID(0x1106),
//                                                                            new javax.bluetooth.UUID(0x1115),
//                                                                            new javax.bluetooth.UUID(0x1116),
//                                                                            new javax.bluetooth.UUID(0x1117) 
                                                                            };
        return searchUuidSet;
    }

}
